package com.rzico.sbl.ui.manager

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMasterBarrelBinding
import com.rzico.sbl.model.BarrelData
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.textTrim
import com.xinnuo.common.extend.visible
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class MasterBarrelActivity : BaseActivity(R.layout.activity_master_barrel) {

    private val mBinding by lazy { ActivityMasterBarrelBinding.bind(getRootView()) }
    private var mState = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<MasterViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initTabLayout()
        initLayout()
        initSearch()

        observe<String>("barrelList") {
            getViewModel()
                .delay { updateList() }
        }
    }

    private fun initTabLayout() {
        val index = intent.getIntExtra("index", 1)

        mBinding.barrelTab.apply {
            onTabSelectedListener {
                onTabSelected {
                    it?.let {
                        mState = when (it.position) {
                            0 -> "unconfirmed"
                            1 -> "dispatch"
                            2 -> "delivery"
                            3 -> "completed"
                            else -> ""
                        }

                        getViewModel().cancelRequest()
                        getViewModel().delay { updateList() }
                    }
                }
            }

            addTab(
                newTab().apply {
                    setCustomView(R.layout.tablayout_item_custom)
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待分配"
                },
                index == 1
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.tablayout_item_custom)
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "已分配"
                },
                index == 2
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.tablayout_item_custom)
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待核销"
                },
                false
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.tablayout_item_custom)
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "已完成"
                },
                false
            )
        }
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关退桶信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            barrelCount()
                            getData(0)
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<BarrelData>(R.layout.item_master_barrel) { jector, bean, _ ->
                            jector.apply {
                                text(
                                    R.id.item_barrel_time,
                                    "提交时间: ${bean.createDate.getTimeString()}"
                                )
                                text(
                                    R.id.item_barrel_status,
                                    when (bean.status) {
                                        "unconfirmed" -> "待分配"
                                        "dispatch" -> "已分配"
                                        "delivery" -> "待核销"
                                        "completed" -> "已完成"
                                        else -> ""
                                    }
                                )
                                text(R.id.item_barrel_title, bean.name)
                                text(
                                    R.id.item_barrel_price,
                                    "空桶价格: ${bean.pledge.formatDecimal()} 元"
                                )
                                text(R.id.item_barrel_num, "x${bean.subQuantity}")
                                text(R.id.item_barrel_count, bean.subQuantity)
                                text(R.id.item_barrel_total, bean.subPrice.formatDecimal())
                                text(R.id.item_barrel_name, bean.consignee)
                                text(
                                    R.id.item_barrel_phone,
                                    when {
                                        userRole in "1,2"
                                                || privacyStatus == "off" -> bean.phone

                                        else -> bean.phone.phoneReplaceWithStar()
                                    }
                                )
                                text(R.id.item_barrel_addr, bean.address)

                                with<ImageView>(R.id.item_barrel_img) {
                                    it.loadImage(bean.logo)
                                }

                                with<ImageView>(R.id.item_barrel_call) {
                                    it.gone = bean.phone.isEmpty()

                                    it.oneClick {
                                        bean.phone.notEmpty {
                                            showBottomPhoneDialog(this)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_barrel_memo) {
                                    it.text = "买家备注：${bean.memo}"
                                    it.isGone = bean.memo.isNullOrEmpty()
                                }

                                with<TextView>(R.id.item_barrel_memo2) {
                                    it.text = "转派备注：${bean.shippingMemo?.trimEnd('\n')}"
                                    it.isGone = bean.shippingMemo.isNullOrEmpty()
                                }

                                with<TextView>(R.id.item_barrel_pei) {
                                    it.text = "配送员：${bean.adminName}"
                                    it.isVisible = !bean.adminName.isNullOrEmpty()
                                }

                                with<TextView>(R.id.item_barrel_btn1) {
                                    when (bean.status) {
                                        "unconfirmed" -> {
                                            it.text = "转派"
                                            when (userRole) {
                                                "1", "2" -> it.visible()
                                                "3" -> it.gone()
                                            }
                                        }

                                        "dispatch" -> {
                                            it.text = "送达"
                                            it.visible()
                                        }

                                        "delivery" -> {
                                            it.text = "核销"
                                            when (userRole) {
                                                "1", "2" -> it.visible()
                                                "3" -> it.gone()
                                            }
                                        }

                                        else -> it.gone()
                                    }

                                    it.oneClick {
                                        when (bean.status) {
                                            "unconfirmed" -> startActivityEx<MasterBarrelShipActivity>(
                                                "barrelId" to bean.id
                                            )

                                            "dispatch" -> sendBarrel(bean.id)
                                            "delivery" -> offBarrel(bean.id)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_barrel_btn2) {
                                    if (bean.status == "dispatch") {
                                        when (userRole) {
                                            "1", "2" -> {
                                                it.text = "转派"
                                                it.visible()
                                            }

                                            else -> it.gone()
                                        }
                                    } else it.gone()

                                    it.oneClick {
                                        startActivityEx<MasterBarrelShipActivity>("barrelId" to bean.id)
                                    }
                                }

                                with<TextView>(R.id.item_barrel_btn3) {
                                    when (bean.status) {
                                        "unconfirmed", "dispatch" -> {
                                            it.text = "关闭"
                                            when (userRole) {
                                                "1", "2" -> it.visible()
                                                "3" -> it.gone()
                                            }
                                        }

                                        else -> it.gone()
                                    }

                                    it.oneClick { closeBarrel(bean.id) }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .searchLayout
            .apply {
                searchEdit.hint = "请输入姓名、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、电话、地址")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、电话、地址")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    /**
     * 关闭退桶
     */
    private fun closeBarrel(barrelId: String) {
        showHintDialog(
            title = "关闭退桶",
            hint = "确定要关闭退桶订单吗？",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngClose,
                        params = arrayOf("id" to barrelId),
                        onSuccess = {
                            showToast("关闭成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 退桶送达
     */
    private fun sendBarrel(barrelId: String) {
        showHintDialog(
            title = "确认送达",
            hint = "确定要完成送达吗？",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngSend,
                        params = arrayOf("id" to barrelId),
                        onSuccess = {
                            showToast("送达成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 退桶核销
     */
    private fun offBarrel(barrelId: String) {
        showHintDialog(
            title = "确认核销",
            hint = "确定要完成核销吗？",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngOff,
                        params = arrayOf("id" to barrelId),
                        onSuccess = {
                            showToast("核销成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 更新自定义Tab数量
     */
    private fun barrelCount() {
        getViewModel()
            .barrelCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("unconfirmed"),
                            obj.optNotNull("dispatch"),
                            obj.optNotNull("delivery"),
                            mBinding.barrelTab
                        )
                }
            )
    }

    /**
     * 退桶列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .barrelList(
                page = index,
                keyWord = mKeyWord,
                state = mState,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        barrelCount()
        getData(0)
    }

}